<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\blog\admin\controller;

use think\facade\View;
use app\admin\BaseController;
use app\admin\model\User;
use app\admin\model\Catalog;
use app\admin\model\UserGroup;
use app\admin\model\Config;
use plugins\blog\admin\model\BlogNotice;
use plugins\blog\admin\model\BlogCollect;
use plugins\blog\admin\model\BlogComment;
use plugins\blog\admin\model\Blog as BlogModel;
use think\exception\ValidateException;
use plugins\blog\admin\validate\Blog as BlogValidate;
/**
 * 文章
 */
class Blog extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            $search = ['catalog', 'keyword', 'status', 'date', 'attr', 'blog_id'];
            $append = ['attr', 'url'];
            $page = empty($input['page']) ? 1 : $input['page'];
            $pageSize = empty($input['pageSize']) ? 20 : $input['pageSize'];
            $order = ! empty($input['prop']) && ! empty($input['order']) ? [$input['prop'] => $input['order']] : ['istop' => 'desc', 'sort' => 'desc', 'create_time' => 'desc'];
            $count = BlogModel::withSearch($search, $input)->count();
            $data = BlogModel::withSearch($search, $input)->append($append)->order($order)->page($page, $pageSize)->select();
            return json(['status' => 'success','message' => '获取成功', 'data' => $data, 'count' => $count]);
        } else {
            // 权限
            $group = UserGroup::where('status', 1)->order('integral', 'asc')->select();
            // 配置
            $config = Config::getVal('app_blog');
            // 分类
            $catalog = Catalog::field('id,pid,title')->where('theme', theme())->where('type', 'blog')->where('links_type', 0)->where('status', 1)->order('sort', 'desc')->select()->toArray();
            // 分类pid查询
            foreach ($catalog as $key => $val) {
                if (array_search($val['pid'], array_column($catalog, 'id')) === false) $catalog[$key]['pid'] = 0;
            }
            View::assign([
                'group'   => $group,
                'config'  => $config,
                'catalog' => $catalog,
            ]);
            return View::fetch();
        }
    }

    /**
     * 保存新建的资源
     */
    public function save() 
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(BlogValidate::class)->scene('save')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $author = User::where('id', $input['user_id'])->value('nickname');
            BlogModel::create([
                'user_id'              => $input['user_id'],
                'author'               => $author,
                'group_id'             => $input['group_id'],
                'catalog_id'           => $input['catalog_id'],
                'relation'             => $input['relation'],
                'title'                => $input['title'],
                'c_title'              => $input['c_title'],
                'description'          => $input['description'],
                'content'              => $input['content'],
                'cover'                => $input['cover'],
                'images'               => $input['images'],
                'seo_url'              => $input['seo_url'],
                'seo_title'            => $input['seo_title'],
                'seo_keywords'         => $input['seo_keywords'],
                'seo_description'      => $input['seo_description'],
                'field'                => $input['field'],
                'istop'                => array_search('置顶', $input['attr']) !== false ? 1 : 0,
                'isrecommend'          => array_search('推荐', $input['attr']) !== false ? 1 : 0,
                'ishot'                => array_search('热门', $input['attr']) !== false ? 1 : 0,
                'clicks'               => $input['clicks'],
                'create_time'          => empty($input['create_time']) ? date('Y-m-d H:i:s') : $input['create_time'],
                'status'               => $input['status'],
                'sort'                 => $input['sort'],
            ]);
            return json(['status' => 'success', 'message' => '新增成功']);
        }
    }

    /**
     * 保存更新的资源
     */
    public function update() 
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(BlogValidate::class)->scene('update')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $save = BlogModel::find($input['id']);
            if ($input['status'] != $save['status']) {
                $notice = '';
                switch ($input['status']) {
                    case 0:
                        $notice = '重新审核中，请耐心等待';
                        break;
                    case 1:
                        $notice = '审核通过，已被设为全部人可见';
                        break;
                    case 2:
                        $notice = '审核未通过，已被设为仅自己可见';
                        break;
                }
                BlogNotice::create([
                    'to_id'       => $input['user_id'],
                    'user_id'     => 0,
                    'blog_id'     => $input['id'],
                    'notice'      => $notice,
                    'type'        => 3,
                    'unread'      => 0,
                    'create_time' => date('Y-m-d H:i:s'),
                ]);
            }
            $save->user_id             = $input['user_id'];
            $save->group_id            = $input['group_id'];
            $save->catalog_id          = $input['catalog_id'];
            $save->relation            = $input['relation'];
            $save->title               = $input['title'];
            $save->c_title             = $input['c_title'];
            $save->description         = $input['description'];
            $save->author              = $input['author'];
            $save->content             = $input['content'];
            $save->cover               = $input['cover'];
            $save->images              = $input['images'];
            $save->seo_url             = $input['seo_url'];
            $save->seo_title           = $input['seo_title'];
            $save->seo_keywords        = $input['seo_keywords'];
            $save->seo_description     = $input['seo_description'];
            $save->field               = $input['field'];
            $save->istop               = array_search('置顶', $input['attr']) !== false ? 1 : 0;
            $save->isrecommend         = array_search('推荐', $input['attr']) !== false ? 1 : 0;
            $save->ishot               = array_search('热门', $input['attr']) !== false ? 1 : 0;
            $save->clicks              = $input['clicks'];
            $save->create_time         = empty($input['create_time']) ? date('Y-m-d H:i:s') : $input['create_time'];
            $save->status              = $input['status'];
            $save->sort                = $input['sort'];
            $save->save();
            return json(['status' => 'success', 'message' => '修改成功']);
        }
    }
    
    /**
     * 批量修改
     */
    public function batch()
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            foreach ($input['field'] as $key => $field) {
                BlogModel::whereIn('id', $input['id'])->update([$field => $input[$field]]);
            }
            return json(['status' => 'success', 'message' => '修改成功']);
       }
    }

    /**
     * 删除指定资源
     */
    public function delete()
    {
        if ($this->request->isPost()) {
            BlogModel::destroy(input('post.ids'));
            return json(['status' => 'success', 'message' => '删除成功']);
        }
    }
}